<template>
  <el-dialog v-model="visible" :title="form.id ? '修改' : '添加'" @closed="onReset" :close-on-click-modal="false">
    <el-form :model="form" ref="formRef" label-width="100px">
      <el-form-item label="用户名">
        <el-input v-model="form.watch_role" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.name_list" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="角色">
        <el-input v-model="form.phone_list" placeholder="请输入" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="用户类型">
        <el-input v-model="form.duties" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { zhibanAddOrUpdate } from '@/api/dashboard'
import { userOptions, roleOptions, userList } from '@/api/user'
const emit = defineEmits(['refresh'])
const visible = ref(false)
const formRef = ref()
const userOption = ref([])
const roleOption = ref([])
const form = reactive({
  id: 0,
  watch_role: '',
  name_list: '',
  phone_list: '',
  duties: ''
})
const resetForm = JSON.parse(JSON.stringify(form))
const open = (data?) => {
  visible.value = true
  getUserOptions()
  getRoleOptions()
  if (data) Object.assign(form, { ...data })
}
const getUserOptions = () => {
  userOptions().then((res) => {
    userOption.value = res.data.list.map((v) => {
      return {
        label: v.role_name,
        value: v.id
      }
    })
  })
}
const getRoleOptions = () => {
  roleOptions().then((res) => {
    roleOption.value = res.data.map((v) => {
      return {
        label: v.value,
        value: v.group
      }
    })
  })
}
const onConfirm = async () => {
  await formRef.value.validate()
  zhibanAddOrUpdate(form).then(({ msg }: any) => {
    ElMessage.success(msg)
    visible.value = false
    emit('refresh')
  })
}
const onReset = () => {
  Object.keys(resetForm).forEach((item: string) => {
    form[item] = resetForm[item]
  })
}
defineExpose({ open })
</script>

<style lang="scss" scoped></style>
